/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// 平铺数组转树形结构用的递归方法
// export function transListToTreeData(list, pid = 0) {
//   const arr = []
//   list.forEach(item => {
//     // 说明找到了 pid 对应的子级部门
//     if (item.pid === pid) {
//       // item 就是子部门
//       arr.push(item)
//       // 子部门中还要继续查找它的子部门
//       const children = transListToTreeData(list, item.id)
//       if (children.length) {
//         item.children = children
//       }
//     }
//   })
//   return arr
// }

export function transListToTreeData(list, pid = 1) {
  const arr = []
  list.forEach(item => {
    // 说明找到了 pid 对应的子级部门
    if (item.pid === pid) {
      // item 就是子部门
      arr.push(item)
      // 子部门中还要继续查找它的子部门
      item.children = transListToTreeData(list, item.id)
    }
  })
  return arr
}

// 处理excel表格，把中文表格转英文的
export function transExcel(res) {
  // 先写一个映射关系
  const mapInfo = {
    姓名: 'username',
    手机号: 'mobile',
    入职日期: 'timeOfEntry',
    转正日期: 'correctionTime',
    工号: 'workNumber',
    部门: 'departmentName'
  }
  // 返回的是一个数组对象
  return res.map((ele) => {
    const enObj = {}
    // 1.拿到所有的中文key
    // 2.将中文key转为英文key
    Object.keys(ele).forEach(item => {
      const enKey = mapInfo[item]
      // 先判断如果是入职时间timeOfEntry和转正时间correctionTime要处理一下时间格式
      // 3.拼装成英文对象
      if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
        enObj[enKey] = formatExcelDate(ele[item])
      } else {
        enObj[enKey] = ele[item]
      }
    })
    return enObj
  })
}

// 处理excel中时间显示问题的函数
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

import EmployeeConst from '@/constant/employees.js'
// 处理excel表格，把英文表格转中文的
export function transExcelHeader(list) {
  // 把数组转成  obj:{'1':'正式', '2':'非正式'}，然后用obj["1"]就可以获取到,不用放到formOfEmployment函数里面，不用每次都循环
  const hireType = {}
  EmployeeConst.hireType.forEach(ele => (hireType[ele.id] = ele.value))
  // 先写一个映射关系
  const mapInfo = {
    id: 'ID',
    username: '用户名',
    staffPhoto: '头像',
    mobile: '手机号',
    workNumber: '工号',
    departmentId: '部门id',
    departmentName: '部门名称',
    timeOfEntry: '入职时间',
    formOfEmployment: '聘用形式'
  }

  return list.rows.map(ele => {
    const zhObj = {}
    // console.log(Object.keys(ele))
    Object.keys(ele).forEach((item) => {
      if (item === 'formOfEmployment') {
        ele[item] = hireType[ele[item]]
      }
      zhObj[ mapInfo[item]] = ele[item]
    })
    return zhObj
  })
}

